package weibo.acitivity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;


import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.whu.administrator.ws.MyApplication;
import com.whu.administrator.ws.R;
import com.whu.administrator.ws.UIHandler;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import chat.utils.MapUtil;
import utils.TimeUtil;
import weibo.dto.BlogData;
import weibo.network.SendWeibo;

/**
 * 测算面积
 * Created by 凯 on 2015/11/25.
 */
public class SendWeiboActivity extends UIHandler.BaseActivity {


    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
    .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
    .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
//    .cacheInMemory(true)//设置下载的图片是否缓存在内存中
//    .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
    .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
    .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
    .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
    .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
            .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
            .build();//构建完成

    Button btn_back;
    View btn_upload;

    String[] files = new String[6];

    {
        files = new String[]{"img0.jpg", "img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg", "img5.jpg"};
    }

    final String filehead = "/sdcard/myappimg/";
    List<ImageView> imageViews = new ArrayList<ImageView>();
    View v_take;
    View v_poplayout;
    Button v_takePhoto;
    Button v_choosePhoto;
    Button v_cancel;

    EditText et_text;

    int num = 0;// 当前已拍照照片数目

    // 已经拍摄的图片路径
    List<String> filenames = new ArrayList<String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uploadpoints);

        initviews();
    }


    View.OnClickListener itemclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_upload) {
                new AlertDialog.Builder(SendWeiboActivity.this).setTitle("发送").
                        setMessage("输入完毕，确认发送？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        sendPhotos();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }

                }).show();


            } else if (v == btn_back) {
                finish();
            } else if (v == v_take) {
                if (num == 6) return;
                clickImgView(imageViews, num);
            } else if (v == v_cancel) {
                openPopView(false);
            } else if (v == v_takePhoto) {
                openPopView(false);
                takephoto(files[num]);
            } else if (v == v_choosePhoto) {
                choosephoto();
                openPopView(false);
            }

        }
    };

    // 发送信息
    private void sendPhotos() {
        SendWeibo sendWeibo = new SendWeibo();
        BlogData blogData = new BlogData();
        blogData.setBlog_Text(et_text.getText().toString());
        blogData.setBlog_Time(TimeUtil.currentTime());
        if (filenames.size() == 0)
        {
            blogData.setBlog_Type("text");
        }
        else
        {
            blogData.setBlog_Type("image");
        }
        StringBuffer sb = new StringBuffer();
        String head = System.currentTimeMillis()+"_";
        for(int i=0;i<filenames.size();i++)
        {
            sb.append(head+new File(filenames.get(i)).getName()).append(";");
        }
        Log.i("fileset",sb.toString());

        blogData.setImage_Set(sb.toString());
        blogData.setImage_Num(filenames.size());
        blogData.setUser_ID(Long.parseLong(MyApplication.getOwnUser().getUser_ID()));
        sendWeibo.setBlogData(blogData);
        List<File> files = new ArrayList<File>();
        for (String n:filenames)
        {
            files.add(new File(n));
        }
        sendWeibo.setFiles(files);

        SendWeiBoTask sendWeiBoTask = new SendWeiBoTask();
        sendWeiBoTask.execute(sendWeibo);
    }

    // 打开popview
    public void openPopView(boolean open) {
        if (open) {
            TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            mShowAction.setDuration(500);
            v_poplayout.startAnimation(mShowAction);
            v_poplayout.setVisibility(View.VISIBLE);
        } else {
            TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    1.0f);
            mHiddenAction.setDuration(500);
            v_poplayout.startAnimation(mHiddenAction);
            v_poplayout.setVisibility(View.GONE);
        }
    }

    // 点击拍照图标
    private void clickImgView(List<ImageView> imageViews, int i) {
//        imageViews.get(i).setVisibility(View.VISIBLE);
//        takephoto(files[i]);
//        this.i = i;

        openPopView(true);
    }

    // 拍照的文件名
    public void takephoto(String filename) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File filedir = new File("/sdcard/myappimg/");
        if (!filedir.exists()) {
            filedir.mkdir();
        }
        File file = new File(filehead + filename);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, 0x02);
    }


    // 选择照片
    public void choosephoto() {
        try {
            //选择照片的时候也一样，我们用Action为Intent.ACTION_GET_CONTENT，
            //有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 3);
        } catch (ActivityNotFoundException e) {

        }
    }

    // 初始化
    private void initviews() {
        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemclick);

        btn_upload = findViewById(R.id.id_btn_send);
        btn_upload.setOnClickListener(itemclick);

        imageViews.add((ImageView) findViewById(R.id.id_img_take1));
        imageViews.add((ImageView) findViewById(R.id.id_img_take2));
        imageViews.add((ImageView) findViewById(R.id.id_img_take3));
        imageViews.add((ImageView) findViewById(R.id.id_img_take4));
        imageViews.add((ImageView) findViewById(R.id.id_img_take5));
        imageViews.add((ImageView) findViewById(R.id.id_img_take6));

        v_take = findViewById(R.id.id_v_take);
        v_take.setOnClickListener(itemclick);

        v_poplayout = findViewById(R.id.pop_layout);
        v_takePhoto = (Button) findViewById(R.id.btn_take_photo);
        v_choosePhoto = (Button) findViewById(R.id.btn_pick_photo);
        v_cancel = (Button) findViewById(R.id.btn_cancel);
        v_takePhoto.setOnClickListener(itemclick);
        v_choosePhoto.setOnClickListener(itemclick);
        v_cancel.setOnClickListener(itemclick);

        et_text = (EditText) findViewById(R.id.id_et_text);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) return;
        if (requestCode == 0)
            return;

        if (requestCode == 0x02) {
            ImageLoader.getInstance().displayImage("file:///mnt" + filehead + files[num], imageViews.get(num), options, listener);

            return;
        }

        if (requestCode == 0x03) {
            if (data != null) {
                //取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
                Uri mImageCaptureUri = data.getData();
                //返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
                if (mImageCaptureUri != null) {
                    Log.i("路径", getRealFilePath(this, mImageCaptureUri));
                    String filePath = getRealFilePath(this, mImageCaptureUri);
                    ImageLoader.getInstance().displayImage("file:/" + filePath, imageViews.get(num), options, listener);
                    return;
                }
            }
        }

    }

    // 图片加载
    ImageLoadingListener listener = new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            Log.i("imgUri", imageUri);
            filenames.add(imageUri.substring(6));
            imageViews.get(num).setVisibility(View.VISIBLE);
            num++;
        }
    };


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    // 发送微博
    class SendWeiBoTask extends AsyncTask
    {


        @Override
        protected Object doInBackground(Object[] params) {
            SendWeibo sendWeibo = (SendWeibo) params[0];
            Boolean success = Boolean.FALSE;
            try {
                success = sendWeibo.upload();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return success;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o == Boolean.TRUE)
            {
                Toast.makeText(MyApplication.share(),"发送成功",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(MyApplication.share(),"发送失败",Toast.LENGTH_SHORT).show();
            }
        }
    }

}
